#—*— coding: utf-8 —*—
__author__ = 'rsj217'


import re
from django import forms
from django.contrib.auth.models import User
from django.db.models import Q
from models import Account
from utils import detect_identifier_type


class SigninForm(forms.Form):

    username = forms.CharField(
        label=u'用户名',
        max_length=40,
        help_text=u'手机号或者邮箱'
    )
    password = forms.CharField(
        label=u'密码',
        max_length=40,
        widget=forms.PasswordInput
    )
    remeber_me = forms.BooleanField(
        label=u'记住我',
        required=False
    )

    def clean_username(self):
        username = self.cleaned_data['username']
        identifier_type = detect_identifier_type(username)
        if identifier_type != 'email' and identifier_type != 'phone':
            raise forms.ValidationError(u'请输入正确的手机号或者邮箱')
        return username

    #def clean_password(self):
    #
    #    password = self.cleaned_data['password']
    #    print password
    #    if len(password) < 5:
    #        raise forms.ValidationError(u'密码至少需要六个字符.')
    #    return password


class SignupForm(forms.Form):

    username = forms.CharField(
        label=u'用户名',
        help_text=u'手机号或者邮箱'
    )
    password = forms.CharField(
        label=u'密码',
        widget=forms.PasswordInput,
        help_text=u'六位以上的数字或者字母组成的密码'
    )
    confirm = forms.CharField(
        label=u'确认密码',
        widget=forms.PasswordInput,
        help_text=u'请再输入一遍密码'
    )

    def clean_username(self):

        username = self.cleaned_data['username']
        identifier_type = detect_identifier_type(username)

        if identifier_type == 'email':
            filter = Q(email=username)
        elif identifier_type == 'phone':
            filter = Q(account__phone=username)
        else:
            raise forms.ValidationError(u'请输入正确的手机号或者邮箱')

        self.cleaned_data['identifier_type'] = identifier_type

        try:
            active_user = User.objects.get(filter)
            raise forms.ValidationError(u'该用户已经存在')
        except User.DoesNotExist:
            return username

    def clean_password(self):

        password = self.cleaned_data['password']
        if len(password) < 5:
            raise forms.ValidationError(u'密码至少需要六个字符.')
        return password

    def clean_confirm(self):
        if 'password' in self.cleaned_data:
            password = self.cleaned_data['password']
            confirm = self.cleaned_data['confirm']
            if 5 < len(password) < 20:
                if password == confirm:
                    return confirm
                else:
                    raise forms.ValidationError(u'两次输入密码不一样')
            else:
                raise forms.ValidationError(u'密码至少需要六个字符.')





